package ru.fivestarter.multileveledcache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import java.util.Map;

import java.util.Set;

import ru.fivestarter.multileveledcache.cache.Cache;
import ru.fivestarter.multileveledcache.cache.marshall.SerializableEntry;
import ru.fivestarter.multileveledcache.cachecreator.CacheCreator;
import ru.fivestarter.multileveledcache.strategy.StrategyVariation;

public class MultiLeveledCache implements Cache {
    /**
     * @associates <{ru.fivestarter.multileveledcache.cache.Cache}>
     */
    private List<Cache> caches;

    /**
     * @associates <{ru.fivestarter.multileveledcache.cachecreator.CacheCreator}>
     */
    private Set<CacheCreator> cacheCreators;
    public MultiLeveledCache(CacheCreator cacheCreator1,StrategyVariation strategyVariation1,int size1,
                             CacheCreator cacheCreator2,StrategyVariation strategyVariation2,int size2){
        cacheCreators=new HashSet<CacheCreator>();
        cacheCreators.add(cacheCreator1);
        cacheCreators.add(cacheCreator2);
        caches=new ArrayList<Cache>();
        caches.add(cacheCreator1.createCache((strategyVariation1),size1));
        caches.add(cacheCreator2.createCache((strategyVariation2),size2));
        
    }
    

    @Override
    public Map.Entry<String, Object> add(String key, Object value) {
        int i=0;
        Map.Entry entry=new SerializableEntry<String, Object>(key,value);
        do{
            entry = caches.get(i).add((String)entry.getKey(), entry.getValue());
            
            
        }while(i++<caches.size()&&entry!=null);
        return null;
    }

    @Override
    public Object find(String key) {
        Cache cache;
        Object result=null;
        Iterator iterator = caches.iterator();
        while (iterator.hasNext()){
            cache=(Cache)iterator.next();
            result=cache.find(key);
            if(result!=null)
                return result;
        }
        return result;
    }

    @Override
    public Map.Entry remove(String key) {
        Cache cache;
        Map.Entry entry=null;
        Iterator iterator = caches.iterator();
        while (iterator.hasNext()){
            cache=(Cache)iterator.next();
            entry=cache.remove(key);
            if(entry!=null)
                return entry;
        }
        return entry;
    }

    @Override
    public void clear() {
        Cache cache;
        Iterator iterator = caches.iterator();
        while (iterator.hasNext()){
            cache=(Cache)iterator.next();
            cache.clear();
        }
    }
}
